﻿//<my-matriculator - a simple tool for registering racers in a USAC cyclocross race>
//Copyright (C) <2011>  <Steven Rivers>

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Xml.Linq;
using System.IO;
using Registration.Model;
using Registration.Model.Entities;


namespace Registration
{
    /// <summary>
    /// Interaction logic for Tools.xaml
    /// </summary>
    public partial class Tools
    {
        public Tools()
        {
            InitializeComponent();
        }

        private void ClickConvertToXml(object sender, RoutedEventArgs e)
        {
            var dlg = new Microsoft.Win32.OpenFileDialog {DefaultExt = ".csv", Filter = "CSV Files (.csv)|*.csv"};
            var result = dlg.ShowDialog();

            if (result != true) return;
            string filename = dlg.FileName;

            if (File.Exists(Config.GetDatabasePath() + "usacdb.xml"))
            {
                if (MessageBoxResult.Cancel == MessageBox.Show("usacdb.xml File Already exists. Overwrite?", "Confirm", MessageBoxButton.OKCancel))
                {
					return;
                }
            }
            var source = File.ReadAllLines(filename);
            source = CleanArray(source);

            var theData = new XElement("NewDataSet",
                                       from str in source
                                       let fields = str.Split(',')
                                       select new XElement("Racer",
                                            new XElement("License", fields[0]),
                                            new XElement("LastName", fields[1]),
                                            new XElement("FirstName", fields[2]),
                                            new XElement("City", fields[3]),
                                            new XElement("State", fields[4]),
                                            new XElement("Gender", fields[5]),
                                            new XElement("RacingAge", fields[6]),
                                            new XElement("ExpDate", fields[7]),
                                            new XElement("Club", fields[8]),
                                            new XElement("Team", fields[9]),
                                            new XElement("NCAA", fields[10]),
                                            new XElement("CrossCategory", fields[11])));
            theData.Save(Config.GetDatabasePath() + "usacdb.xml");
        }

        private static string[] CleanArray(string[] source)
        {
            var clean = new List<string>(source);
            clean.RemoveAt(0);
            source = clean.ToArray();
            return source;
        }

        private void ClickExportEntries(object sender, RoutedEventArgs e)
        {
            var dlg = new Microsoft.Win32.SaveFileDialog { DefaultExt = ".csv", Filter = "CSV Files (.csv)|*.csv" };
            var result = dlg.ShowDialog();
            if (result == false) return;
            EntryDb.WriteEntriesToCsv(dlg.FileName);
        }

        private void ClickBackup(object sender, RoutedEventArgs e)
        {
            BackupDatasets.Backup();
        }

        private void ClickEditFields(object sender, RoutedEventArgs e)
        {
            var window = new FieldsSetup();
            window.Show();
        }

        private void ClickSearchDatabase(object sender, RoutedEventArgs e)
        {
            var window = new SearchWindow(String.Empty);
            window.Show();
        }

        private void ClickImportEntries(object sender, RoutedEventArgs e)
        {
            var dlg = new Microsoft.Win32.OpenFileDialog {DefaultExt = ".csv", Filter = "CSV Files (.csv)|*.csv"};
            var result = dlg.ShowDialog();
            if (result != true) return;
            var filename = dlg.FileName;

            String[] source = File.ReadAllLines(filename);
            source = CleanArray(source);

            foreach (var fields in source.Select(s => s.Split(',')))
            {
                int license;
                Int32.TryParse(fields[0], out license);
                var racer = UsacDb.GetRacer(license) ??
                            UsacDb.FindRider(fields[3], fields[2]) ??
                            new UsacRider(license, fields[3], fields[2], "", "", fields[5], "", "12/31/2011", fields[4], "", "", "");

                var fieldname = fields[1];
                var cat = FieldsDb.FindCategory(fieldname) ??
                          FieldsDb.FindCategoryWithMap(fieldname);


                if (cat == null)
                {
                    var configdlg = new ConfigMapping(fieldname);
                    var updated = configdlg.ShowDialog();
                    if (updated == true)
                    {
                        cat = FieldsDb.FindCategoryWithMap(fieldname);
                    }
                }

                if (cat == null) continue;
                var f = FieldsDb.GetFieldUpdateBib(cat.CategoryField);
                var entry = new Entry(-1, f.NextBib, racer.License, cat.CategoryId, cat.CategoryName, racer.FirstName, racer.LastName, racer.Club, racer.Gender, racer.RacingAge);
                EntryDb.AddEntry(entry);
            }
        }
    }
}
